<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">用户名：</span>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.username"
      />
      <span class="search-label">姓名：</span>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
      />
      <span class="search-label">角色：</span>
      <el-select v-model="params.roleName">
        <el-option
          v-for="item in roleIdList"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <div class="block">
        <span class="demonstration"></span>
        <el-date-picker
          style="margin-left: 5px"
          v-model="value2"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        >
        </el-date-picker>
      </div>
      <el-button type="primary" class="search-btn" @click="search"
        >查询</el-button
      >
    </div>
    <el-button @click="handleExportExcel">导出excel表</el-button>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="100"
        />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="角色" prop="roleName" />
        <el-table-column label="时间" prop="time" :formatter="formatTime" />
        <el-table-column label="ip地址" prop="ipAddress" />
        <el-table-column label="设备" prop="device" />
        <el-table-column label="操作" prop="status" :formatter="formatStatus" />
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>


<script>
import { getAllClassesAPI } from "@/api/classes";
import { getAllLoginRecordsByPageAPI,exportExcelAPI } from "@/api/loginRecord";

export default {
  name: "Check_results",
  data() {
    return {
      // 角色表单参数
      roleIdList: [
        {
          text: "全部",
          value: "",
        },
        {
          text: "超级管理员",
          value: "超级管理员",
        },
        {
          text: "普通管理员",
          value: "普通管理员",
        },
        {
          text: "学生",
          value: "学生",
        },
        {
          text: "老师",
          value: "老师",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      Rules: {},
      Form: {
        studentInfoId: "",
        classId: "",
      },
      colleges: [],
      open: false,
      selecttionVal: [],
      classs: [],
      total: 0, //页总数
      list: [], //列表
      params: {
        //参数
        page: 1,
        pageSize: 2,
        username: "",
        name: "",
        roleName: "",
        startTime: null,
        endTime: null,
      },
    };
  },
  created() {
    this.getAllLoginRecordsByPage();
    this.getAllClasses();
  },
  computed: {
    computedParams() {
      const startTime =
        this.value2 && this.value2.length > 0 ? new Date(this.value2[0]) : null;

      const endTime =
        this.value2 && this.value2.length > 1 ? new Date(this.value2[1]) : null;

      return {
        ...this.params,
        startTime: startTime,
        endTime: endTime,
      };
    },
  },
  watch: {
    value2(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.params.startTime =
          newValue && newValue.length > 0 ? new Date(newValue[0]) : null;
        this.params.endTime =
          newValue && newValue.length > 1 ? new Date(newValue[1]) : null;
      }
    },
  },
  methods: {
    handleExportExcel() {
      exportExcelAPI(this.params)
        .then(response => {
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'scores.xlsx';
          link.click();

          window.URL.revokeObjectURL(link.href);
        })
        .catch(error => {
          console.error('Failed to export Excel:', error);
        });
    },
    formatDate(date) {
      // 格式化时间为 YYYY-MM-DD HH:mm:ss 格式
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //格式化时间
    formatTime(row) {
      const date = new Date(row.time);
      return this.formatDate(date);
    },
    //格式化状态
    formatStatus(row) {
      const MAP = {
        0: "登录",
        1: "退出",
      };
      return MAP[row.status];
    },
    //获取学院数据
    async getAllColleges() {
      const res = await getAllCollegesAPI();
      this.colleges = res.data;
    },
    //提交表格
    submitForm() {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        if (this.Form.studentInfoId != "") {
          //修改操作
          await editStudentClassAPI(this.Form);
          this.$message.success("修改成功");
          this.getAllClasses();
        } else {
          //新增操作
          this.$message.success("添加成功");
        }
        this.open = false;
        this.getAllLoginRecordsByPage();
      });
    },
    //编辑按钮
    async edit(studentInfoId, className) {
      this.Form.studentInfoId = studentInfoId;
      //找到班级名称对应的班级Id
      const oneclass = this.classs.find((item) => item.className === className);
      this.Form.classId = oneclass.classId;
      this.open = true;
    },
    //获取学生分页数据
    async getAllLoginRecordsByPage() {
      const res = await getAllLoginRecordsByPageAPI(this.params);
      this.total = res.data.total;
      this.list = res.data.records;
    },
    //获取班级列表
    async getAllClasses() {
      const res = await getAllClassesAPI();
      this.classs = res.data;
    },
    //多选框输入值
    selectBlur(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.className = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear() {
      this.params.className = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange(val) {
      this.params.className = val;
      this.$forceUpdate();
    },
    //点击查询按钮
    search() {
      this.params.page = 1;
      this.getAllLoginRecordsByPage();
    },
    //计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    //页数改变
    handleCurrentChange(val) {
      this.params.page = val;
      this.getAllLoginRecordsByPage();
    },
    //页条数改变
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getAllLoginRecordsByPage();
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>